<?php

/**
 * 单页管理
 */

namespace app\ph\controller;

class Page extends Base
{
    protected $page_model;

    public function __construct()
    {
        parent::__construct();
        $this->page_model = new \app\common\model\Page();
    }

    /**
     * 列表功能
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $where = [];
        $field = 'title,id,create_time';
        $data  = $this->page_model->getList($where, $field);
        $page  = $data->render();
        $data  = $data->items();
        return view('page/index',
            [
                'data' => $data,
                'page' => $page
            ]
        );
    }

    /**
     * 添加
     * @return \think\response\View
     */
    public function data_insert()
    {
        return view('page/data_insert');
    }

    /**
     * 修改
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function data_update($id)
    {
        if (!$id) {
            $this->error('缺失参数ID');
        }
        $data = $this->page_model->getOne(['id' => $id], '*', 'id desc');
        if (!$data) {
            $this->error('获取信息失败');
        }
        return view('page/data_update',
            [
                'data' => $data
            ]
        );
    }

    /**
     * 数据操作
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function data_save()
    {
        $data['title'] = input('post.title');
        if (!$data['title']) {
            return json(['code' => 100, 'message' => '请填写标题']);
        }
        $data['content'] = htmlspecialchars_decode(input('post.content'));
        if (!$data['content']) {
            return json(['code' => 100, 'message' => '请填写内容']);
        }
        $data['create_time'] = strtotime(input('post.create_time')) ? strtotime(input('post.create_time')) : time();
        $id                  = input('post.id');
        if ($id) {
            $data['update_time'] = time();
            $res                 = $this->page_model->editData(['id' => $id], $data);
        } else {
            // 增加缓存
            $res = $this->page_model->addData($data);
        }
        return operationResult($res, url('Page/Index'));
    }


    /**
     * 删除
     * @return \think\response\Json
     */
    public function data_delete()
    {
        $id = input('post.id');
        if (!$id) {
            return json(['code' => 100, 'message' => '缺失ID参数']);
        }
        $res = $this->page_model->dataDelete($id);
        return operationResult($res);
    }
}
